import React, { useState, useEffect, useCallback } from "react";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ProjectAPI } from "@/api/project";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/components/ui/use-toast";
import {
  Plus,
  Search,
  MapPin,
  Upload,
  Building2,
  CheckCircle,
  User,
  Edit,
  Trash2,
  FileText,
  Lightbulb,
  BarChart2,
  FileDown,
  MoreHorizontal,
  Navigation,
  Ruler,
  Zap,
  Wind,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  AlertTriangle,
  WifiOff,
} from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

import CrossingPointForm from "../components/crossingpoints/CrossingPointForm";
import CrossingPointFilters from "../components/crossingpoints/CrossingPointFilters";
import CrossingPointImportModal from "../components/crossingpoints/CrossingPointImportModal";
import SchemeForm from "../components/schemes/SchemeForm";
import SmartRecommendationModal from "../components/crossingpoints/SmartRecommendationModal";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

const CONSTANTS = {
  difficultyTexts: {
    low: "低难度",
    medium: "中等难度",
    high: "高难度",
    critical: "极高难度",
  },
  priorityTexts: {
    low: "低优先级",
    medium: "中等优先级",
    high: "高优先级",
    urgent: "紧急",
  },
  statusTexts: {
    planning: "规划中",
    designed: "已设计",
    approved: "已批准",
    construction: "施工中",
    completed: "已完成",
  },
  typeIcons: {
    highway: "🛣️",
    railway: "🚆",
    river: "🌊",
    cable: "🔌",
    pipeline: "🔧",
    building: "🏢",
    forest: "🌲",
    other: "📍",
  },
};

// 颜色工具函数 - 统一使用设计系统色彩

export default function CrossingPoints() {
  // 状态定义
  const [crossingPoints, setCrossingPoints] = useState([]);
  const [projects, setProjects] = useState([]);
  const [schemes, setSchemes] = useState([]);
  const [filteredPoints, setFilteredPoints] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingPoint, setEditingPoint] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filters, setFilters] = useState({
    projectId: "all",
    crossingType: "all",
    status: "all",
    priority: "all",
    difficultyLevel: "all",
  });
  const [isLoading, setIsLoading] = useState(true);
  const [showSmartRecommendation, setShowSmartRecommendation] = useState(false);
  const [selectedCrossingPoint, setSelectedCrossingPoint] = useState(null);
  const [selectedPoints, setSelectedPoints] = useState(new Set());
  const [showImportModal, setShowImportModal] = useState(false);
  const [recommendations, setRecommendations] = useState([]);

  const [isRatingModalOpen, setIsRatingModalOpen] = useState(false);
  const [pointForRating, setPointForRating] = useState(null);
  const [showManualSchemeForm, setShowManualSchemeForm] = useState(false);
  const [pointForManualScheme, setPointForManualScheme] = useState(null);
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [showRecommendationModal, setShowRecommendationModal] = useState(false);
  const [recommendationData, setRecommendationData] = useState(null);
  const [isGeneratingDoc, setIsGeneratingDoc] = useState(false);
  const [recLoading, setRecLoading] = useState(false);

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);

  // 错误处理相关状态
  const [error, setError] = useState(null);
  const [retryCount, setRetryCount] = useState(0);
  const [isRetrying, setIsRetrying] = useState(false);

  const location = useLocation();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [crossingTypeMap, setCrossingTypeMap] = useState([]);
  const [isLoadingVoltage, setIsLoadingVoltage] = useState(true);

  useEffect(() => {
    const loadVoltageLevels = async () => {
      try {
        setIsLoadingVoltage(true);

        // 1. 获取所有字典类型（包含电压等级）
        const typeResponse = await DictTypeAPI.getList();
        if (typeResponse.code !== 200 || !typeResponse?.rows?.length) {
          throw new Error("获取字典类型失败");
        }

        // 2. 从返回的rows中找到"电压等级"的字典类型
        const voltageType = typeResponse.rows.find(
          (item) => item.dictName === "跨越类型"
        );

        if (!voltageType || !voltageType.dictType) {
          throw new Error("未找到跨越类型的dictType");
        }

        // 3. 使用dictType获取具体的电压等级数据（关键修改点）
        const dataResponse = await DictDataAPI.getList({
          dictType: voltageType.dictType, // 这里使用dictType而不是dictId
        });

        if (dataResponse.code !== 200 || !dataResponse?.rows) {
          throw new Error("获取跨越类型数据失败");
        }

        // 4. 格式化数据为Select组件所需格式，并按排序号排序
        const formattedLevels = dataResponse.rows
          .sort((a, b) => (a.dictSort || 0) - (b.dictSort || 0))
          .map((item) => ({
            value: item.dictValue,
            label: item.dictLabel,
          }));
        console.log(formattedLevels, "formattedLevels");
        setCrossingTypeMap(formattedLevels);
      } catch (error) {
      } finally {
        setIsLoadingVoltage(false);
      }
    };

    loadVoltageLevels();
  }, []);

  const getCrossingTypeLabel = (type) => {
    const matched = crossingTypeMap.find((item) => item.value === type);
    return matched ? matched.label : type || "未指定";
  };

  // 数据加载和过滤逻辑
  useEffect(() => {
    loadData();
  }, [currentPage, itemsPerPage]);

  const filterPoints = useCallback(() => {
    const urlParams = new URLSearchParams(location.search);
    const pointId = urlParams.get("id");

    if (pointId) {
      const filtered = crossingPoints.filter((p) => p.id === pointId);
      setFilteredPoints(filtered);
      setTotalItems(filtered.length);
      return;
    }

    let filtered = crossingPoints;

    if (searchTerm) {
      filtered = filtered.filter(
        (point) =>
          point.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          point.code?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          point.crossingObject?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (filters.projectId !== "all") {
      filtered = filtered.filter(
        (point) => point.projectId === filters.projectId
      );
    }

    if (filters.status === "Created") {
      filtered = filtered.filter((point) => point.isScheme === true);
    } else if (filters.status === "onCreated") {
      filtered = filtered.filter((point) => point.isScheme === false);
    }

    Object.keys(filters).forEach((key) => {
      if (key !== "projectId" && key !== "status" && filters[key] !== "all") {
        filtered = filtered.filter((point) => point[key] === filters[key]);
      }
    });

    setTotalItems(filtered.length);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    setFilteredPoints(filtered.slice(startIndex, endIndex));
  }, [
    crossingPoints,
    searchTerm,
    filters,
    location.search,
    currentPage,
    itemsPerPage,
  ]);

  useEffect(() => {
    filterPoints();
    const urlParams = new URLSearchParams(location.search);
    const pointIdToEdit = urlParams.get("edit");
    if (pointIdToEdit && crossingPoints.length > 0) {
      const point = crossingPoints.find((p) => p.id === pointIdToEdit);
      if (point) {
        handleEdit(point);
        const newParams = new URLSearchParams(location.search);
        newParams.delete("edit");
        navigate(`${location.pathname}?${newParams.toString()}`, {
          replace: true,
        });
      }
    }
  }, [
    crossingPoints,
    filterPoints,
    location.search,
    location.pathname,
    navigate,
  ]);

  // 数据加载函数
  const loadData = async (isRetry = false) => {
    if (isRetry) {
      setIsRetrying(true);
      setError(null);
    } else {
      setIsLoading(true);
      setError(null);
    }

    try {
      if (isRetry && retryCount > 0) {
        await new Promise((resolve) =>
          setTimeout(resolve, Math.min(2000 * retryCount, 10000))
        );
      }

      const [pointsData, projectsData, schemesData, templatesData] =
        await Promise.all([
          CrossingPointAPI.getList(),
          ProjectAPI.getList(),
          ConstructionSchemeAPI.getList(),
          ConstructionMethodTemplateAPI.getList(),
        ]);

      setCrossingPoints(Array.isArray(pointsData.data) ? pointsData.data : []);
      setProjects(Array.isArray(projectsData.data) ? projectsData.data : []);
      setSchemes(Array.isArray(schemesData.data) ? schemesData.data : []);
      setMethodTemplates(
        Array.isArray(templatesData.data) ? templatesData.data : []
      );

      setError(null);
      setRetryCount(0);
    } catch (error) {
      console.error("加载数据失败:", error);
      const errorMessage = error.message || "未知错误";
      const isNetworkError =
        errorMessage.includes("500") ||
        errorMessage.includes("timeout") ||
        errorMessage.includes("ServerSelectionTimeoutError") ||
        errorMessage.includes("No replica set members") ||
        (error.name === "TypeError" &&
          error.message.includes("Failed to fetch"));

      setError({
        message: errorMessage,
        isNetworkError,
        canRetry: true,
      });

      if (!isRetry) {
        setCrossingPoints([]);
        setProjects([]);
        setSchemes([]);
        setMethodTemplates([]);
        setTotalItems(0);
      }
    } finally {
      setIsLoading(false);
      setIsRetrying(false);
    }
  };

  // 事件处理函数
  const handleRetry = () => {
    setRetryCount((prev) => prev + 1);
    loadData(true);
  };

  useEffect(() => {
    if (error && error.isNetworkError && retryCount < 3) {
      const timer = setTimeout(() => {
        console.log(`自动重试第 ${retryCount + 1} 次...`);
        handleRetry();
      }, 5000 + retryCount * 2000);

      return () => clearTimeout(timer);
    }
  }, [error, retryCount]);

  const handleSearch = (term) => {
    setSearchTerm(term);
    setCurrentPage(1);
  };

  const handleFilterChange = (newFilters) => {
    setFilters(newFilters);
    setCurrentPage(1);
  };

  const handleSubmit = async (pointData) => {
    try {
      if (editingPoint) {
        await CrossingPointAPI.update(editingPoint.id, pointData);
      } else {
        await CrossingPointAPI.create(pointData);
      }
      setShowForm(false);
      setEditingPoint(null);
      await loadData();
    } catch (error) {
      console.error("保存跨越点失败:", error);
      alert("保存失败: " + (error.message || "未知错误"));
    }
  };

  const handleEdit = (point) => {
    setEditingPoint(point);
    setShowForm(true);
  };

  const handleDeletePoint = async (pointId) => {
    if (window.confirm("确定要删除此跨越点吗？无法撤销。")) {
      try {
        await CrossingPointAPI.delete(pointId);
        loadData();
        // if (deletedSchemesCount > 0) {
        //   alert(
        //     `跨越点删除成功！同时删除了 ${deletedSchemesCount} 个关联的施工方案。`
        //   );
        // } else {
        //   alert("跨越点删除成功！");
        // }
        loadData();
      } catch (error) {
        console.error("删除跨越点失败:", error);
        alert("删除跨越点失败，请稍后重试。");
      }
    }
  };

  const handleBatchDelete = async () => {
    if (selectedPoints.size === 0) {
      alert("请先选择要删除的跨越点");
      return;
    }
    if (
      !window.confirm(
        `确定要删除选中的 ${selectedPoints.size} 个跨越点吗？此操作将同时删除所有关联的施工方案，且无法撤销。`
      )
    ) {
      return;
    }

    try {
      setIsLoading(true);
      let totalDeletedSchemes = 0;
      let totalDeletedPoints = 0;

      for (const pointId of selectedPoints) {
        try {
          const resData = await ConstructionSchemeAPI.filter(pointId);
          console.log(resData, "resDataresData");

          // const relatedSchemes = resData.data;
          // for (const scheme of relatedSchemes) {
          //   await ConstructionSchemeAPI.delete(scheme.id);
          //   totalDeletedSchemes++;
          // }

          // await CrossingPointAPI.delete(pointId);
          // totalDeletedPoints++;
        } catch (error) {
          console.error(`删除跨越点 ${pointId} 失败:`, error);
        }
      }

      alert(
        `批量删除完成！删除了 ${totalDeletedPoints} 个跨越点和 ${totalDeletedSchemes} 个关联的施工方案。`
      );
      setSelectedPoints(new Set());

      if (filteredPoints.length === selectedPoints.size && currentPage > 1) {
        setCurrentPage((prev) => prev - 1);
      } else {
        loadData();
      }
    } catch (error) {
      console.error("批量删除失败:", error);
      alert("批量删除过程中发生错误，请检查控制台日志。");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelectAll = () => {
    if (selectedPoints.size === filteredPoints.length) {
      setSelectedPoints(new Set());
    } else {
      setSelectedPoints(new Set(filteredPoints.map((p) => p.id)));
    }
  };

  const handleSelectPoint = (pointId) => {
    const newSelected = new Set(selectedPoints);
    if (newSelected.has(pointId)) {
      newSelected.delete(pointId);
    } else {
      newSelected.add(pointId);
    }
    setSelectedPoints(newSelected);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingPoint(null);
  };

  const getProjectName = (projectId) => {
    const project = projects.find((p) => p.id === projectId);
    return project ? project.projectName : "未知项目";
  };

  const getLatestSchemeForPoint = (pointId) => {
    const pointSchemes = schemes.filter((s) => s.crossingPointId === pointId);
    if (pointSchemes.length === 0) return null;

    return pointSchemes.sort(
      (a, b) =>
        new Date(b.createdDate).getTime() - new Date(a.createdDate).getTime()
    )[0];
  };

  const handleRatingConfirm = async (ratingResult) => {
    if (!pointForRating) {
      toast({
        title: "操作失败",
        description: "未找到关联的跨越点信息",
        variant: "destructive",
      });
      return;
    }

    try {
      const schemeData = {
        approvalStatus: "notStarted",
        constructionMethod: ratingResult.selectedMethod.template.id,
        crossingPointId: ratingResult.pointId,
        name: `系统评分推荐方案-${
          pointForRating.name
        }-${new Date().toLocaleDateString()}`,
        version: ratingResult.selectedMethod.template.version,
      };

      toast({
        title: "正在创建施工方案",
        description: "系统正在根据评分推荐生成施工方案...",
      });

      const response = await ConstructionSchemeAPI.create(schemeData);

      toast({
        title: "方案创建成功",
        description: `已为 ${pointForRating.name} 生成施工方案`,
      });

      setIsRatingModalOpen(false);
      setPointForRating(null);
      loadData();
    } catch (error) {
      console.error("处理评分推荐失败:", error);
      toast({
        title: "操作失败",
        description:
          error.response?.data?.message || "评分推荐处理出错，请重试",
        variant: "destructive",
      });
    }
  };

  const handleCreateScheme = async (schemeData) => {
    try {
      await ConstructionSchemeAPI.create(schemeData);
      toast({
        title: "方案创建成功",
        description: `已为 ${schemeData.crossingPointName} 生成智能推荐施工方案`,
      });
      loadData();
      setShowRecommendationModal(false);
    } catch (error) {
      console.error("智能创建方案失败:", error);
      toast({
        title: "操作失败",
        description:
          error.response?.data?.message || "智能推荐处理出错，请重试",
        variant: "destructive",
      });
    }
  };

  const handleManualCreateScheme = (point) => {
    setPointForManualScheme(point);
    setShowManualSchemeForm(true);
  };

  const handleManualSchemeSubmit = async (schemeData) => {
    try {
      await ConstructionSchemeAPI.create(schemeData);
      setShowManualSchemeForm(false);
      setPointForManualScheme(null);
      alert("施工方案已手动创建！请在施工方案管理中查看和编辑。");
      loadData();
    } catch (error) {
      console.error("手动创建方案失败:", error);
      alert("手动创建方案失败: " + (error.message || "未知错误"));
    }
  };

  const handleSchemeCreated = (newScheme) => {
    toast({
      title: "方案创建成功",
      description: `施工方案"${newScheme.name}"已创建，可在施工方案管理中查看`,
    });

    loadData();
    setShowSmartRecommendation(false);
    setSelectedCrossingPoint(null);
    setRecommendations([]);
  };

  const handleImportSuccess = () => {
    setShowImportModal(false);
    loadData();
  };

  const getTypeIcon = (type) => {
    return CONSTANTS.typeIcons[type] || "📍";
  };

  const generateMockRecommendation = (scheme) => {
    const baseScenario = scheme.crossingType
      ? {
          highway: "公路跨越场景",
          railway: "铁路跨越场景",
          river: "河流跨越场景",
        }[scheme.crossingType] || "通用场景"
      : "通用场景";

    return {
      code: 0,
      data: {
        advantages: [
          "施工效率高，相比传统方法可缩短工期30%",
          "安全性高，采用双重防护措施",
          "对周边环境影响小，符合环保要求",
          "材料消耗低，可节约成本约15%",
        ],
        alternativeMethods: [
          {
            alternativeMethod: {
              applicableScenarios: ["跨越高速公路", "跨越二级以下公路"],
              methodName: "悬索式跨越施工法",
              version: "1.1",
            },
            reason: "适用于跨度较大的场景，但施工成本较高",
          },
        ],
        confidence: 0.85,
        considerations: [
          "施工期间需注意天气变化，遇大风天气应停止作业",
          "需提前与交通部门协调，做好交通疏导方案",
        ],
        methodTemplate: {
          id: "11ebb6a2805749f790757154837ea365",
          methodName: "脚手架跨越施工法",
          applicableScenarios: ["跨越二级以下公路", "跨越不通航河流"],
        },
        reasoning:
          "根据该跨越点的参数分析，脚手架跨越施工法最为适用，具有成本低、安全性高等优势。",
      },
      msg: "success",
    };
  };

  const handleSmartRecommendation = async (point) => {
    setRecLoading(true);
    try {
      if (!point?.id) {
        throw new Error("未找到有效的跨越点ID");
      }

      await new Promise((resolve) => setTimeout(resolve, 1000));
      const mockData = generateMockRecommendation(point);

      if (!mockData || mockData.code !== 0 || !mockData.data) {
        throw new Error("推荐数据生成失败");
      }

      setRecommendationData(mockData.data);
      setSelectedCrossingPoint(point);
      setShowRecommendationModal(true);

      toast({
        title: "推荐成功",
        description: "已为您生成智能推荐方案",
      });
    } catch (error) {
      console.error("智能推荐失败:", error);
      toast({
        variant: "destructive",
        title: "推荐失败",
        description: error.message || "生成智能推荐时发生错误，请稍后重试",
      });
    } finally {
      setRecLoading(false);
    }
  };

  const handleGenerateDocument = async (schemeId) => {
    setIsGeneratingDoc(true);
    try {
      const response = await ConstructionSchemeAPI.exportWord(schemeId);

      if (!(response.data instanceof Blob)) {
        throw new Error("后端返回的不是二进制文件流");
      }

      const rawFileName =
        response.headers["download-filename"] ||
        response.headers["Download-Filename"];

      let downloadFileName = rawFileName
        ? decodeURIComponent(rawFileName)
        : `施工方案_${schemeId}.docx`;

      if (!downloadFileName.endsWith(".docx")) {
        downloadFileName += ".docx";
      }

      const wordMimeType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      const fileBlob = new Blob([response.data], { type: wordMimeType });

      const url = window.URL.createObjectURL(fileBlob);
      const a = document.createElement("a");
      a.href = url;
      a.download = downloadFileName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error("生成文档错误:", error);
      toast({
        variant: "destructive",
        title: "生成Word失败",
        description: "方案信息不完整/未选择文档模板，无法进行分析。",
      });
    } finally {
      setIsGeneratingDoc(false);
    }
  };

  // 分页控制函数
  const handlePageChange = (page) => {
    const totalPages = Math.ceil(totalItems / itemsPerPage) || 1;
    if (page < 1 || page > totalPages) return;
    setCurrentPage(page);
    document
      .querySelector(".overflow-x-auto")
      ?.scrollIntoView({ behavior: "smooth" });
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1);
  };

  const totalPages = Math.ceil(totalItems / itemsPerPage) || 1;

  // 渲染错误状态
  const renderError = () => (
    <Card className="text-center py-12 border-slate-200 shadow-sm">
      <div className="space-y-4">
        {error.isNetworkError ? (
          <WifiOff className="w-16 h-16 text-rose-300 mx-auto" />
        ) : (
          <AlertTriangle className="w-16 h-16 text-rose-300 mx-auto" />
        )}
        <div>
          <h3 className="text-lg font-semibold text-slate-900 mb-2">
            {error.isNetworkError ? "网络连接问题" : "加载失败"}
          </h3>
          <p className="text-slate-500 mb-4">
            {error.isNetworkError
              ? "数据库连接暂时不稳定，请稍后重试"
              : error.message}
          </p>
        </div>
        <div className="flex justify-center gap-3">
          <Button
            onClick={handleRetry}
            disabled={isRetrying || retryCount >= 3}
            className="bg-blue-600 hover:bg-blue-700"
          >
            {isRetrying ? (
              <>
                <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                重试中... {retryCount > 0 && `(${retryCount}/3)`}
              </>
            ) : (
              <>
                <RefreshCw className="w-4 h-4 mr-2" />
                重试
              </>
            )}
          </Button>
          <Button variant="outline" onClick={() => window.location.reload()}>
            刷新页面
          </Button>
        </div>
      </div>
    </Card>
  );

  // 渲染分页控件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-6 py-4 border-t border-slate-200 bg-white">
      <div className="text-sm text-slate-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>

          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}

          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="p-6 bg-slate-50 min-h-screen">
      <div className="max-w-7xl mx-auto space-y-6">
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 p-4 bg-white rounded-lg shadow-sm border border-slate-200">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 mb-1">
              交叉跨越点管理
            </h1>
            <p className="text-slate-500">管理输电线路跨越点信息和施工难点</p>
          </div>
          <div className="flex gap-3 w-full lg:w-auto">
            <Button
              onClick={() => setShowForm(true)}
              className="bg-blue-600 hover:bg-blue-700 flex items-center gap-2 flex-1 lg:flex-none"
            >
              <Plus className="w-4 h-4" />
              新建跨越点
            </Button>
          </div>
        </div>

        {/* Search and Filters - 统一搜索筛选区域样式 */}
        <div className="p-4 bg-white rounded-lg shadow-sm border border-slate-200">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
              <Input
                placeholder="搜索跨越点名称、编号或跨越对象..."
                value={searchTerm}
                onChange={(e) => handleSearch(e.target.value)}
                className="pl-10"
              />
            </div>
            <CrossingPointFilters
              filters={filters}
              onFilterChange={handleFilterChange}
              projects={projects}
              className="w-full lg:w-auto"
            />
          </div>
        </div>

        {/* 网络错误提示 */}
        {error && !isLoading && (
          <Alert
            variant={error.isNetworkError ? "default" : "destructive"}
            className="mb-4"
          >
            <AlertTriangle className="h-4 w-4" />
            <AlertTitle>
              {error.isNetworkError ? "连接不稳定" : "加载错误"}
            </AlertTitle>
            <AlertDescription className="flex items-center justify-between">
              <span>
                {error.isNetworkError
                  ? `正在尝试重新连接 (${retryCount}/3)，部分功能可能受影响。`
                  : error.message}
              </span>
              {!isRetrying && retryCount < 3 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleRetry}
                  className="ml-4"
                >
                  <RefreshCw className="w-4 h-4 mr-1" />
                  重试
                </Button>
              )}
              {retryCount >= 3 && error.isNetworkError && (
                <span className="text-sm text-slate-500 ml-4">
                  请检查网络或稍后刷新页面
                </span>
              )}
            </AlertDescription>
          </Alert>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card className="border-slate-200 shadow-sm hover:shadow-md transition-shadow">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">总跨越点</p>
                  <p className="text-2xl font-bold text-slate-900 mt-1">
                    {crossingPoints.length}
                  </p>
                </div>
                <Building2 className="w-8 h-8 text-blue-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-sm hover:shadow-md transition-shadow">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">高难度</p>
                  <p className="text-2xl font-bold text-rose-700 mt-1">
                    {
                      crossingPoints.filter(
                        (p) =>
                          p.difficultyLevel === "high" ||
                          p.difficultyLevel === "critical"
                      ).length
                    }
                  </p>
                </div>
                <AlertTriangle className="w-8 h-8 text-rose-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-sm hover:shadow-md transition-shadow">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">高优先级</p>
                  <p className="text-2xl font-bold text-orange-700 mt-1">
                    {
                      crossingPoints.filter(
                        (p) => p.priority === "high" || p.priority === "urgent"
                      ).length
                    }
                  </p>
                </div>
                <Zap className="w-8 h-8 text-orange-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="border-slate-200 shadow-sm hover:shadow-md transition-shadow">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-slate-600">已完成</p>
                  <p className="text-2xl font-bold text-emerald-700 mt-1">
                    {
                      crossingPoints.filter((p) => p.status === "completed")
                        .length
                    }
                  </p>
                </div>
                <CheckCircle className="w-8 h-8 text-emerald-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 表单模态框 */}
        {showForm && (
          <CrossingPointForm
            point={editingPoint}
            projects={projects}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            isStandalone={true}
          />
        )}

        <CrossingPointImportModal
          isOpen={showImportModal}
          onClose={() => setShowImportModal(false)}
          projectId={filters.projectId !== "all" ? filters.projectId : null}
          onImportSuccess={handleImportSuccess}
          projects={projects}
        />

        {showManualSchemeForm && pointForManualScheme && (
          <SchemeForm
            scheme={null}
            selectedCrossingPoint={pointForManualScheme}
            crossingPoints={[pointForManualScheme]}
            methodTemplates={methodTemplates}
            onSubmit={handleManualSchemeSubmit}
            onCancel={() => setShowManualSchemeForm(false)}
          />
        )}

        <SmartRecommendationModal
          isOpen={showRecommendationModal}
          onClose={() => setShowRecommendationModal(false)}
          crossingPoint={selectedCrossingPoint}
          recommendation={recommendationData}
          onSchemeCreated={handleCreateScheme}
        />

        {/* 主表格区域 - 增强视觉层次感 */}
        <Card className="border border-slate-200 shadow-sm overflow-hidden">
          {error && !isLoading && crossingPoints.length === 0 ? (
            renderError()
          ) : (
            <div className="">
              <Table>
                <TableHeader className="bg-slate-50 border-b border-slate-200">
                  <TableRow>
                    <TableHead className="px-6 py-3 text-left font-medium text-slate-700">
                      名称
                    </TableHead>
                    <TableHead className="px-6 py-3 text-left font-medium text-slate-700">
                      项目
                    </TableHead>
                    <TableHead className="px-6 py-3 text-left font-medium text-slate-700">
                      跨越对象
                    </TableHead>
                    <TableHead className="px-6 py-3 text-left font-medium text-slate-700">
                      跨越类型
                    </TableHead>
                    {/* <TableHead className="px-6 py-3 text-left font-medium text-slate-700">勘查单</TableHead> */}
                    <TableHead className="w-[80px] px-6 py-3 text-right font-medium text-slate-700">
                      操作
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={7} className="h-40 text-center">
                        <div className="flex flex-col items-center justify-center">
                          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mb-4"></div>
                          <p className="text-slate-500">加载跨越点中...</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : filteredPoints.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={7} className="h-40 text-center">
                        <div className="flex flex-col items-center justify-center">
                          <MapPin className="w-16 h-16 text-slate-300 mb-4" />
                          <h3 className="text-lg font-semibold text-slate-900 mb-2">
                            {searchTerm ||
                            Object.values(filters).some((f) => f !== "all") ||
                            location.search.includes("id=")
                              ? "未找到匹配的跨越点"
                              : "暂无跨越点"}
                          </h3>
                          <p className="text-slate-500 mb-6">
                            {searchTerm ||
                            Object.values(filters).some((f) => f !== "all") ||
                            location.search.includes("id=")
                              ? "请尝试调整搜索条件或筛选器"
                              : "创建您的第一个跨越点"}
                          </p>
                          {!searchTerm &&
                            Object.values(filters).every((f) => f === "all") &&
                            !location.search.includes("id=") && (
                              <div className="flex gap-3 justify-center">
                                <Button
                                  onClick={() => setShowImportModal(true)}
                                  variant="outline"
                                  className="bg-emerald-600 text-white hover:bg-emerald-700"
                                >
                                  <Upload className="w-4 h-4 mr-2" />
                                  批量导入
                                </Button>
                                <Button
                                  onClick={() => setShowForm(true)}
                                  className="bg-blue-600 hover:bg-blue-700"
                                >
                                  <Plus className="w-4 h-4 mr-2" />
                                  新建跨越点
                                </Button>
                              </div>
                            )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredPoints.map((point, index) => {
                      const latestScheme = getLatestSchemeForPoint(point.id);
                      const isSelected = selectedPoints.has(point.id);
                      const projectName = getProjectName(point.projectId);
                      // 增强的表格行样式 - 更清晰的隔行效果
                      const rowBg =
                        index % 2 === 0 ? "bg-white" : "bg-slate-50";

                      return (
                        <TableRow
                          key={point.id}
                          className={`${rowBg} border-b border-slate-100 hover:bg-slate-100/70 transition-colors`}
                        >
                          <TableCell className="px-6 py-4 font-medium">
                            <div className="flex items-center">
                              <div
                                className="text-sm font-medium text-slate-900  max-w-[150px] cursor-pointer"
                                onClick={() => handleEdit(point)}
                              >
                                {point.name || "未命名跨越点"}
                              </div>
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="text-sm text-slate-500  max-w-[120px]">
                              {projectName}
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="flex items-center">
                              <span className="mr-2">
                                {getTypeIcon(point.crossingType)}
                              </span>
                              <span className="text-sm text-slate-900  max-w-[120px]">
                                {point.crossingObject || "未指定"}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="text-sm text-slate-900  max-w-[150px]">
                              {getCrossingTypeLabel(point.crossingType)}
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4 text-right">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button
                                  variant="outline"
                                  size="icon"
                                  className="h-8 w-8 hover:bg-slate-100 transition-colors"
                                >
                                  <MoreHorizontal className="h-4 w-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                {latestScheme ? (
                                  <>
                                    <DropdownMenuItem
                                      onClick={() =>
                                        navigate(
                                          createPageUrl(
                                            `SchemeAnalysis?id=${latestScheme.id}`
                                          )
                                        )
                                      }
                                      className="cursor-pointer"
                                    >
                                      <BarChart2 className="w-4 h-4 mr-2" />
                                      分析
                                    </DropdownMenuItem>
                                    <DropdownMenuItem
                                      onClick={() =>
                                        handleGenerateDocument(latestScheme.id)
                                      }
                                      disabled={isGeneratingDoc}
                                      className="cursor-pointer"
                                    >
                                      {isGeneratingDoc ? (
                                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
                                      ) : (
                                        <FileDown className="w-4 h-4 mr-2" />
                                      )}
                                      文档
                                    </DropdownMenuItem>
                                  </>
                                ) : (
                                  <></>
                                )}
                                <DropdownMenuItem
                                  onClick={() => handleEdit(point)}
                                  className="cursor-pointer"
                                >
                                  <Edit className="w-4 h-4 mr-2" />
                                  编辑
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={() => handleDeletePoint(point)}
                                  className="text-rose-600 focus:text-rose-600 cursor-pointer"
                                >
                                  <Trash2 className="w-4 h-4 mr-2" />
                                  删除
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </div>
          )}
          {!error && !isLoading && totalItems > 0 && renderPagination()}
        </Card>
      </div>
    </div>
  );
}
